import os
import cgi
import datetime
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

from User import User

class DataHandler(webapp.RequestHandler):

    def post(self):
        self.response.headers["Content-Type"] = "application/json"
        
        userid = self.request.get("userid")
        angelOrDevil = self.request.get("angelordevil")
        
        if userid == "" or angelOrDevil == "":
            self.response.out.write("error")
            return
        
        user = self.getUser(userid)    
        # user logged in before ?
        if not user is None: 
            # and voted ?
            if user.isVoted: 
                self.response.out.write(self.getJSONResult(userid, True, True))
                return
            else:
                user.isVoted = True
                user.put()
                self.response.out.write(self.getJSONResult(userid, True, True))
                return
        else:
            self.saveVote(userid, angelOrDevil)
            self.response.out.write(self.getJSONResult(userid, True, True))
            return
        
        
    def get(self):
        self.response.headers["Content-Type"] = "application/json"
        
        userid = self.request.get("userid")
        if userid != "":               
            user = self.getUser(userid)    
            # user logged in before ?
            if not user is None: 
                # and voted ?
                if user.isVoted: 
                    self.response.out.write(self.getJSONResult(userid, True, True))
                    return
                # but not voted !
                else:            
                    self.response.out.write(self.getJSONResult(userid, True, False))
                    return
            # never logged in !
            else:                
                self.response.out.write(self.getJSONResult(userid, False, False))  
                return                                  
        # ERROR userid is not supplied !
        else:
            self.response.out.write(self.getJSONResult(userid, False, False))
            return    
            
    def saveVote(self, userid, angelOrDevil):
        user = User()
        user.userId = int(userid)
        user.isVoted = True
        if angelOrDevil == "angel":
            user.isAngel = True
        elif angelOrDevil == "devil":
            user.isAngel = False
        
        user.put()        
    
    def getJSONResult(self, userid, loggedBefore, voted):   
        if loggedBefore and voted:
            numOfAngel = self.getNumOfAngel()
            numOfDevil = self.getNumOfDevil()
            isAngel = False
            if voted:
                isAngel = self.getIsAngel(userid)
            return self.getJSON(loggedBefore, voted, numOfAngel, numOfDevil, isAngel)
        else:
            return self.getJSON(loggedBefore, voted, 0, 0, False)                    
        
    def getJSON(self, loggedBefore, voted, numOfAngel, numOfDevil, isAngel):
        if voted:
            return """{
                 "loggedBefore" :""" + str(loggedBefore).lower() + """,
                 "voted" :""" + str(voted).lower() +""",
                 "numOfAngel" : """ + str(numOfAngel) + """,
                 "numOfDevil" : """ + str(numOfDevil) + """,
                 "isAngel" : """ + str(isAngel).lower() + """                            
               }"""
        else:
            return """{
                 "loggedBefore" :""" + str(loggedBefore).lower() + """,
                 "voted" :""" + str(voted).lower() +""",
                 "numOfAngel" : """ + str(numOfAngel) + """,
                 "numOfDevil" : """ + str(numOfDevil) + """                            
               }"""
                            
    def getUser(self, userid):
        query = User.all()
                
        if query.filter("userId =", int(userid)).count() > 0:
            return query.filter("userId = ", int(userid)).get()
        else:
            return None
    
    def getIsAngel(self, userid):
        return self.getUser(userid).isAngel
    
    def getNumOfAngel(self):
        query = User.all()        
        return query.filter("isAngel =", True).count()
    
    def getNumOfDevil(self):
        query = User.all()        
        return query.filter("isAngel =", False).count()
        